from StuManSys import app, db
from StuManSys.main.model import UserData
import bcrypt


class Database:
    def __init__(self):
        pass

    def write_userdata(self, data: dict) -> int:
        """
        data:
            email: varchar 25,
            password varchar 20,
            birth_date date,
        return:
            1: 注册成功
            2: 用户邮箱已存在
            0: 数据库操作失败
        """
        email = data['email']
        password = data['password']
        birth_date = data['birth_date']

        try:
            with app.app_context():
                # 检查 email 是否已经存在
                existing_user = UserData.query.filter_by(email=email).first()

                if existing_user:
                    return 2  # 用户邮箱已存在
                else:
                    # 哈希密码
                    hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')

                    # 创建新用户
                    new_user = UserData(
                        email=email,
                        password=hashed_password,
                        birth_date=birth_date
                    )

                    # 添加到数据库
                    db.session.add(new_user)
                    db.session.commit()

                    print(f'{email}注册成功')
                    return 1  # 注册成功

        except Exception as e:
            print(f"数据库操作失败: {e}")
            db.session.rollback()
            return 0  # 数据库操作失败

    def read_userdata(self, data: dict) -> int:
        '''
        email: str
        password: str
        return: 
            1: 登录成功
            2: 用户不存在 
            3: 密码错误
            0: 数据库操作失败
        '''
        email = data['email']
        password = data['password']

        try:
            with app.app_context():
                # 检查 email 是否存在
                user = UserData.query.filter_by(email=email).first()

                if user is None:
                    return 2  # 用户不存在
                else:
                    # 比较密码
                    stored_password = user.password.encode('utf-8')
                    pswd_bytes = password.encode('utf-8')

                    if bcrypt.checkpw(pswd_bytes, stored_password):
                        return 1  # 登陆成功
                    else:
                        return 3  # 密码错误

        except Exception as e:
            print(f"数据库操作失败: {e}")
            return 0  # 数据库操作失败


if __name__ == '__main__':
    db_handler = Database()

    # 测试注册
    email = 'test@gmail.com'
    password = '123456'
    data = {
        'email': email,
        'password': password,
        'birth_date': '2004-01-01'
    }
    state = db_handler.write_userdata(data)
    print(f"注册状态: {state}")

    # 测试登录
    login_data = {
        'email': email,
        'password': password,
    }
    state = db_handler.read_userdata(login_data)
    print(f"登录状态: {state}")